function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
import "antd/es/tree/style";
import _Tree from "antd/es/tree";
import "antd/es/empty/style";
import _Empty from "antd/es/empty";
import "antd/es/spin/style";
import _Spin from "antd/es/spin";
import "antd/es/button/style";
import _Button from "antd/es/button";
import "antd/es/input/style";
import _Input from "antd/es/input";
var _excluded = ["treeData", "title", "showSearch", "showReset", "loading", "showTitle", "id", "className", "style", "defaultExpandedKeys", "showFiltered", "onSelect", "actions", "defaultSelectedKeys", "selectEmptyAble"],
  _excluded2 = ["key", "title"];
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { withNativeProps } from "../utils/native-props";
import classnames from 'classnames';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { treeFilter } from "../utils/tree";
import { SyncOutlined, MoreOutlined } from '@ant-design/icons';
import Actions from "./components/Actions";
import "./index.less";
import { useDebounceFn } from 'ahooks';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var getParentKey = function getParentKey(key, tree) {
  var parentKey;
  for (var i = 0; i < tree.length; i++) {
    var node = tree[i];
    if (node.children) {
      if (node.children.some(function (item) {
        return item.key === key;
      })) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
export default function SearchTree(props) {
  var defaultValue = useRef({
    treeData: [],
    defaultExpandedKeys: [],
    defaultSelectedKeys: []
  });
  var _props$treeData = props.treeData,
    treeData = _props$treeData === void 0 ? defaultValue.current.treeData : _props$treeData,
    _props$title = props.title,
    title = _props$title === void 0 ? '组织结构' : _props$title,
    _props$showSearch = props.showSearch,
    showSearch = _props$showSearch === void 0 ? true : _props$showSearch,
    _props$showReset = props.showReset,
    showReset = _props$showReset === void 0 ? false : _props$showReset,
    _props$loading = props.loading,
    loading = _props$loading === void 0 ? false : _props$loading,
    _props$showTitle = props.showTitle,
    showTitle = _props$showTitle === void 0 ? true : _props$showTitle,
    id = props.id,
    className = props.className,
    style = props.style,
    _props$defaultExpande = props.defaultExpandedKeys,
    defaultExpandedKeys = _props$defaultExpande === void 0 ? defaultValue.current.defaultExpandedKeys : _props$defaultExpande,
    _props$showFiltered = props.showFiltered,
    showFiltered = _props$showFiltered === void 0 ? false : _props$showFiltered,
    _onSelect = props.onSelect,
    _props$actions = props.actions,
    actions = _props$actions === void 0 ? [] : _props$actions,
    _props$defaultSelecte = props.defaultSelectedKeys,
    defaultSelectedKeys = _props$defaultSelecte === void 0 ? defaultValue.current.defaultSelectedKeys : _props$defaultSelecte,
    _props$selectEmptyAbl = props.selectEmptyAble,
    selectEmptyAble = _props$selectEmptyAbl === void 0 ? true : _props$selectEmptyAbl,
    rest = _objectWithoutProperties(props, _excluded);
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    expandedKeys = _useState2[0],
    setExpandedKeys = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    searchValue = _useState4[0],
    setSearchValue = _useState4[1];
  var _useState5 = useState(true),
    _useState6 = _slicedToArray(_useState5, 2),
    autoExpandParent = _useState6[0],
    setAutoExpandParent = _useState6[1];
  var first = useRef(true); // 标志组件第一次拿到值
  var _useState7 = useState([]),
    _useState8 = _slicedToArray(_useState7, 2),
    filterTreeData = _useState8[0],
    setfilterTreeData = _useState8[1]; // 过滤后的树
  var _useState9 = useState([]),
    _useState10 = _slicedToArray(_useState9, 2),
    selectedKeys = _useState10[0],
    setSelectedKeys = _useState10[1];
  var _useState11 = useState({
      visible: false
    }),
    _useState12 = _slicedToArray(_useState11, 2),
    opMenu = _useState12[0],
    setOpMenu = _useState12[1];
  useEffect(function () {
    setfilterTreeData(treeData);
  }, [treeData]);
  useEffect(function () {
    // 设置默认展开节点
    if (first.current && treeData.length > 0) {
      setExpandedKeys(defaultExpandedKeys || []);
      setSelectedKeys(defaultSelectedKeys || []);
      first.current = false;
    }
  }, [defaultExpandedKeys]);
  var onExpand = function onExpand(newExpandedKeys) {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };
  var dataList = useMemo(function () {
    var list = [];
    var generateList = function generateList(data) {
      for (var i = 0; i < data.length; i++) {
        var node = data[i];
        var key = node.key,
          _title = node.title;
        list.push({
          key: key,
          title: _title
        });
        if (node.children) {
          generateList(node.children);
        }
      }
    };
    generateList(treeData);
    return list;
  }, [treeData]);
  var handleSearchChange = function handleSearchChange(value) {
    if (showFiltered) {
      setfilterTreeData(treeFilter(treeData, function (node) {
        return node.title.indexOf(value) > -1;
      }));
    }
    setSearchValue(value);
    if (value) {
      var newExpandedKeys = dataList.map(function (item) {
        var _item$title;
        if ((item === null || item === void 0 ? void 0 : (_item$title = item.title) === null || _item$title === void 0 ? void 0 : _item$title.indexOf(value)) > -1) {
          return getParentKey(item.key, treeData);
        }
        return null;
      }).filter(function (item, i, self) {
        return item && self.indexOf(item) === i;
      });
      setExpandedKeys(newExpandedKeys);
      setAutoExpandParent(true);
    } else {
      setExpandedKeys(defaultExpandedKeys || []);
    }
  };
  var _useDebounceFn = useDebounceFn(function (value) {
      handleSearchChange(value);
    }, {
      wait: 300
    }),
    _onChange = _useDebounceFn.run;
  var handleOp = function handleOp(value) {
    return function (e) {
      e.stopPropagation();
      setOpMenu({
        visible: true,
        left: e.clientX + 10,
        top: e.clientY + 10,
        record: value
      });
    };
  };
  var treeDataWithSearch = useMemo(function () {
    var loop = function loop(data) {
      return data.map(function (item) {
        var key = item.key,
          treeNodeTitle = item.title,
          rest = _objectWithoutProperties(item, _excluded2);
        var strTitle = treeNodeTitle;
        var index = strTitle.indexOf(searchValue);
        var beforeStr = strTitle.substring(0, index);
        var afterStr = strTitle.slice(index + searchValue.length);
        var tipTitle = "".concat(strTitle).concat(item.moreTip || '');
        var title = index > -1 ? /*#__PURE__*/_jsxs("span", {
          title: tipTitle,
          className: "pd-search-tree-node-title",
          children: [/*#__PURE__*/_jsxs("span", {
            className: "pd-search-tree-node-title-content",
            children: [beforeStr, /*#__PURE__*/_jsx("span", {
              className: "pd-search-tree-hilight",
              children: searchValue
            }), afterStr]
          }), !!item.more && item.more, actions.length > 0 && /*#__PURE__*/_jsx("span", {
            style: {
              lineHeight: '24px'
            },
            children: /*#__PURE__*/_jsx(MoreOutlined, {
              onClick: handleOp(item)
            })
          })]
        }) : /*#__PURE__*/_jsxs("span", {
          title: tipTitle,
          className: "pd-search-tree-node-title",
          children: [/*#__PURE__*/_jsx("span", {
            className: "pd-search-tree-node-title-content",
            children: strTitle
          }), !!item.more && item.more, actions.length > 0 && /*#__PURE__*/_jsx("span", {
            style: {
              lineHeight: '24px'
            },
            children: /*#__PURE__*/_jsx(MoreOutlined, {
              onClick: handleOp(item)
            })
          })]
        });
        if (item.children) {
          return _objectSpread(_objectSpread({}, rest), {}, {
            title: title,
            key: key,
            children: loop(item.children)
          });
        }
        return _objectSpread(_objectSpread({}, rest), {}, {
          title: title,
          key: key
        });
      });
    };
    return loop(filterTreeData);
  }, [searchValue, filterTreeData]);

  /** 重置 */
  var handleReset = function handleReset() {
    handleSearchChange('');
    setSelectedKeys(defaultSelectedKeys || []);
    // @ts-ignore
    _onSelect(defaultSelectedKeys || []);
  };
  return withNativeProps(props, /*#__PURE__*/_jsxs("div", {
    className: classnames('pd-search-tree', className),
    id: id,
    style: _objectSpread({}, style),
    children: [showTitle && title && /*#__PURE__*/_jsx("h2", {
      className: "pd-search-tree-title",
      children: title
    }), showSearch && /*#__PURE__*/_jsxs("div", {
      style: {
        display: 'flex'
      },
      className: "pd-search-tree-op",
      children: [/*#__PURE__*/_jsx(_Input.Search, {
        className: "pd-search-tree-input",
        placeholder: "\u8BF7\u8F93\u5165\u5173\u952E\u8BCD\u641C\u7D22",
        allowClear: true,
        onChange: function onChange(e) {
          _onChange(e.target.value);
        }
      }), showReset && /*#__PURE__*/_jsx(_Button, {
        onClick: handleReset,
        className: "pd-search-tree-reset-btn",
        icon: /*#__PURE__*/_jsx(SyncOutlined, {
          style: {
            color: 'rgba(0,0,0,0.45)'
          }
        })
      })]
    }), loading && /*#__PURE__*/_jsx("div", {
      style: {
        display: 'flex',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center'
      },
      children: /*#__PURE__*/_jsx(_Spin, {
        spinning: loading,
        tip: "\u6570\u636E\u52A0\u8F7D\u4E2D..."
      })
    }), !loading && filterTreeData.length === 0 && /*#__PURE__*/_jsx(_Empty, {
      image: _Empty.PRESENTED_IMAGE_SIMPLE,
      description: "\u6682\u65E0\u6570\u636E"
    }), !loading && filterTreeData.length > 0 && /*#__PURE__*/_jsx(_Tree, _objectSpread({
      className: "pd-search-tree-ant-tree",
      onExpand: onExpand,
      expandedKeys: expandedKeys,
      autoExpandParent: autoExpandParent,
      treeData: treeDataWithSearch,
      selectedKeys: selectedKeys,
      onSelect: function onSelect(value, e) {
        if ((value === null || value === void 0 ? void 0 : value.length) === 0 && !selectEmptyAble) {
          return;
        }
        setSelectedKeys(value);
        // @ts-ignore
        _onSelect(value, e);
      }
    }, rest)), /*#__PURE__*/_jsx(Actions, {
      opMenu: opMenu,
      actions: actions,
      setOpMenu: setOpMenu
    })]
  }));
}